package com.example.demo.boot.configuration;

import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;

import javax.annotation.Resource;

@Lazy(false)
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "knife4j.enable", havingValue = "true")
public class Knife4jConfiguration {

    /*引入Knife4j提供的扩展类*/
    @Resource
    private OpenApiExtensionResolver openApiExtensionResolver;
    @Value("${shenyu.client.springCloud.props.contextPath:}")
    private String termsOfServiceUrl;


    @Bean
    public Docket defaultDocket() {
        return createDcket("API", null);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("华数集团")
                .description("华数集团")
                //.termsOfServiceUrl(termsOfServiceUrl)
                .version("1.0")
                .contact(new Contact("浙江华数集团终端管理部", "www.xlqhyl.top", ""))
                .build();
    }

    public Docket createDcket(String group, String antPattern) {
        ApiSelectorBuilder apiSelectorBuilder = new Docket(DocumentationType.OAS_30)
                .host("https://www.xlqhyl.top")
                .apiInfo(apiInfo())
                .groupName(group)
                // 选择那些路径和api会生成document
                .select()
                // 对所有api进行监控
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class));
        //这里可以自定义过滤
        if (StringUtils.isBlank(antPattern)) {
            apiSelectorBuilder.paths(PathSelectors.any());
        } else {
            apiSelectorBuilder.paths(PathSelectors.ant(antPattern));
        }

        return apiSelectorBuilder.build()
                .extensions(openApiExtensionResolver.buildExtensions(group));
    }
}
